# -*- coding: utf-8 -*-
# @Time    : 2021/10/20 10:02
# @Author  : huangwei
# @File    : get_cell3.py
# @Software: PyCharm
import cv2
from skimage import measure

from get_cell2 import get_lines
import numpy as np

from method import draw_box
from table_method import draw_lines, minAreaRectBox

file_path = "images/simple3.png"
img = cv2.imread(file_path)
input_size = (1024, 1024)
rows_lines, cols_lines = get_lines(img, input_size)

# 判断竖线的条数，即分成多少列
# 从左到右排序了，计算x轴距离
x_list = []
for line in cols_lines:
    x1, y1, x2, y2 = line
    cx = (x1 + x2) / 2
    x_list.append(cx)

# 向左合并，即将另一条线左移

col_num = len(cols_lines)

col_index = [0]

lx1, _, lx2, _ = cols_lines[0]
lcx = (lx1 + lx2) / 2

x_index = [lcx]

for i in range(col_num - 1):
    line1 = cols_lines[i]
    line2 = cols_lines[i + 1]

    x1, y1, x2, y2 = line1
    cx1 = (x1 + x2) / 2

    x3, y3, x4, y4 = line2
    cx2 = (x3 + x4) / 2

    dis = abs(cx1 - cx2)

    if dis < 5:
        col_index.append(col_index[-1])
        print("左移第{}条线！".format(i + 1))
        x3 = x3 - dis
        x4 = x4 - dis
        line2 = [x3, y3, x4, y4]
        cols_lines[i + 1] = line2
    else:
        col_index.append(col_index[-1] + 1)
        x_index.append(cx2)

print(col_index)
print(x_index)

# 同理得到y的每一层
y_index = []
for line in rows_lines:
    x1, y1, x2, y2 = line
    cy = (y1 + y2) / 2
    y_index.append(cy)

print(y_index)

# 根据分层为每个box分配坐标和宽高

# 找出格子
# 将找到的所有线都在全黑的图上画出，再在这个图上寻找连通区域即每一个格子
tmp = np.zeros((img.shape[0], img.shape[1]), dtype='uint8')
tmp = draw_lines(tmp, rows_lines + cols_lines, color=255, line_width=1)
tmp_filepath = 'temp_path/tmp.png'
cv2.imwrite(tmp_filepath, tmp)

table_labels = measure.label(tmp == 0, connectivity=2)
regions = measure.regionprops(table_labels)
rboxes = []
for region in regions:
    # print("area:", region.bbox_area)
    if region.bbox_area < img.shape[0] * img.shape[1] / 2:
        rbox = minAreaRectBox(region.coords)
        rboxes.append(rbox)

for box in rboxes:
    draw_box(img, box)
cv2.imwrite("temp_path/box.png", img)
print(len(rboxes))

# 判断box的中心位置在 哪两条竖线两条横线之间确定位置
# 判断box的宽在哪两条竖线之间确定宽度，哪两条横线之间确定高度

box_infos = []
for box in rboxes:
    x1, y1, x2, y2, x3, y3, x4, y4 = box[:8]
    cx = (x1 + x2 + x3 + x4) / 4
    cy = (y1 + y2 + y3 + y4) / 4

    # for m in range(len(x_index)-1):
    #     if x_index[m] < cx < x_index[m + 1]:
    #         box_x_index = m
    #
    # for n in range(len(y_index) - 1):
    #     if y_index[n] < cy < y_index[n+1]:
    #         box_y_index = n

    # 左边竖线中心
    left_x = (x1 + x4) / 2
    min_dis = 500
    box_left_index = 0
    # 找打最铁近的竖线
    for m in range(len(x_index)):
        dis = abs(x_index[m] - left_x)
        if dis < min_dis:
            min_dis = dis
            box_left_index = m

    # 同找另外几条线
    # 上边横线
    up_y = (y1 + y2) / 2
    min_dis = 500
    box_up_index = 0
    for m in range(len(y_index)):
        dis = abs(y_index[m] - up_y)
        if dis < min_dis:
            min_dis = dis
            box_up_index = m

    # 右边竖线
    right_x = (x2 + x3) / 2
    min_dis = 500
    box_right_index = 0
    # 找打最铁近的竖线
    for m in range(len(x_index)):
        dis = abs(x_index[m] - right_x)
        if dis < min_dis:
            min_dis = dis
            box_right_index = m

    # 下边横线
    down_y = (y3 + y4) / 2
    min_dis = 500
    box_down_index = 0
    for m in range(len(y_index)):
        dis = abs(y_index[m] - down_y)
        if dis < min_dis:
            min_dis = dis
            box_down_index = m

    location = [box_left_index, box_up_index, box_right_index - box_left_index, box_down_index - box_up_index]
    print("location:", location)
    box_infos.append(location)

# print(box_infos)

from openpyxl import Workbook
from openpyxl.styles import Alignment, Side, PatternFill
from openpyxl.styles import Border

sheet_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'O', 'P', 'Q']

book = Workbook()
sheet = book.active

for p in range(len(y_index) - 1):
    for k in range(len(x_index) - 1):
        sheet.cell(p + 1, k + 1).border = Border(top=Side(border_style='thin', color='FF000000'),
                                                 right=Side(border_style='thin', color='FF000000'),
                                                 bottom=Side(border_style='thin', color='FF000000'),
                                                 left=Side(border_style='thin', color='FF000000'))
        sheet.cell(p + 1, k + 1).fill = PatternFill("solid", fgColor="E1FFFF")
        sheet.cell(p + 1, k + 1).value = 'a'

for tt in box_infos:
    a, b, c, d = tt
    A = sheet_list[a]
    B = sheet_list[a + c - 1]
    A1 = '{}{}'.format(A, b + 1)
    B2 = '{}{}'.format(B, b + d)
    sheet.merge_cells('{}:{}'.format(A1, B2))
    # sheet['{}'.format(A1)].border = Border(top=Side(border_style='thin', color='FF000000'),
    #                                        right=Side(border_style='thin', color='FF000000'),
    #                                        bottom=Side(border_style='thin', color='FF000000'),
    #                                        left=Side(border_style='thin', color='FF000000'))
    # sheet['{}'.format(A1)].fill = PatternFill("solid", fgColor="E1FFFF")
    # sheet.merge_cells(start_row=b + 1, start_column=a + 1, end_row=b + d + 1, end_column=a + c)
    # sheet.cell(b + 1, a + 1).value = 'test'

    # cell = sheet.cell(row=a + 1, column=b + 1)
    # cell.value = 'Sunny day'
    # cell.alignment = Alignment(horizontal='center', vertical='center')

# tt = box_infos[0]
# a, b, c, d = tt
# print(tt)
# sheet.merge_cells(start_row=b + 1, start_column=a + 1, end_row=b + d, end_column=a + c)
# sheet.cell(b + 1, a + 1).value = 'test'

book.save('merging.xlsx')
